import fetch from "isomorphic-fetch"
import { getCookie } from "../cookie"
import { error } from "antd/lib/notification"

function genertor(response) {
  return response
    .then((res) => {
      if (res.status >= 200 && res.status < 300) {
        return res
      } else {
        error({
          message: res.statusText
        })
      }
    })
    .then(res => res.json())
    .then((res) => {
      const { eCode, message } = res
      if (eCode == 0) {
        return res
      } else {
        error({
          message: message
        })
        return res || {}
      }
    })
    .catch((err) => {
      console.log(err)
      return { eCode: 1 }
    })
}

export async function get(url, option = {}) {
  return genertor(fetch(url, Object.assign(option, {
    method: "GET",
    credentials: "include",
    headers: {
      "Content-type": "application/json",
      "HuoYi-Default-Access-Token": getCookie("token")
    }
  })))
}

export async function post(url, option = {}) {
  return typeof option === "string"
    ? genertor(fetch(url, {
      method: "POST",
      credentials: "include",
      headers: {
        "Content-type": "application/json",
        "HuoYi-Default-Access-Token": getCookie("token")
      },
      body: option
    }))
    : genertor(fetch(url, Object.assign({
      method: "POST",
      credentials: "include",
      headers: {
        "Content-type": "application/json",
        "HuoYi-Default-Access-Token": getCookie("token")
      }
    }, option)))
}

export async function put(url, option = {}) {
  return genertor(fetch(url, Object.assign(option, {
    method: "PUT",
    credentials: "include",
    headers: {
      "content-type": "application/json"
    }
  })))
}

export async function del(url, option = {}) {
  return genertor(fetch(url, Object.assign(option, {
    method: "DELETE",
    credentials: "include",
    headers: {
      "content-type": "application/json"
    }
  })))
}

export const HOST = "./api/";